package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import javafx.scene.shape.Mesh;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkGroupMapper.add(checkGroup);

        setCheckGroupAndCheckItem(checkGroup.getId(), checkitemIds);
    }


    private void setCheckGroupAndCheckItem(Integer id, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            checkGroupMapper.setCheckGroupAndCheckItem(id, checkitemIds);
        }
    }

    /*private void setCheckGroupAndCheckItem(Integer id, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {

                checkGroupMapper.setCheckGroupAndCheckItem(id, checkitemId);
            }
        }
    }*/

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        List<CheckGroup> checkGroupList = checkGroupMapper.findPageByCondition(queryString);
        PageInfo<CheckGroup> pageInfo = new PageInfo<>(checkGroupList);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public CheckGroup findById(Integer id) {
        CheckGroup checkGroup = checkGroupMapper.findById(id);
        return checkGroup;
    }

    @Override
    public Integer[] findCheckItemIdsByCheckGroupId(Integer id) {
        Integer[] checkItemIds = checkGroupMapper.findCheckItemIdsByCheckGroupId(id);
        return checkItemIds;
    }

    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkGroupMapper.deleteAssociation(checkGroup.getId());

        checkGroupMapper.edit(checkGroup);

        setCheckGroupAndCheckItem(checkGroup.getId(), checkitemIds);

    }

    @Override
    public void deleteById(Integer id) {
      Integer count = checkGroupMapper.findCountFromAssociation(id);
        if (count > 0) {
            throw new RuntimeException(MessageConstant.DELETE_CHECKGROUP_FAIL);
        }

        checkGroupMapper.deleteAssociation(id);

        checkGroupMapper.deleteById(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }
}